package com.example.tanhuanapp;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class MD5WithSaltExample {
    public static void main(String[] args) {
        String password = "123456"; // 要加密的密码
        String salt = generateSalt(); // 生成随机盐值

        String hashedPassword = md5WithSalt(password, salt); // 对密码进行MD5加密并添加盐值
        System.out.println("Hashed Password: " + hashedPassword);
    }

    // 生成随机盐值
    private static String generateSalt() {
        SecureRandom random = new SecureRandom();
        byte[] saltBytes = new byte[16];
        random.nextBytes(saltBytes);
        return Base64.getEncoder().encodeToString(saltBytes);
    }

    // 对密码进行MD5加密并添加盐值
    private static String md5WithSalt(String password, String salt) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(salt.getBytes()); // 添加盐值
            byte[] hashedBytes = md.digest(password.getBytes());
            return Base64.getEncoder().encodeToString(hashedBytes);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }
}
